const { rollup } = require('rollup');
const uglify = require('uglify-js');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
/**
 * 递归创建目录
 * mkdirp('./tmp/foo/bar/baz', function (err) { // 在当前目录下创建多级文件夹
 *     console.log(err);
 * });
 */
const mkdirpNode = require('mkdirp');
/**
 * 将一个接收回调函数参数的函数转换成一个返回Promise的函数
 * 如上面的mkdirp函数
 */
const { promisify } = require('util');
const { configs, utils, paths, uglifyOptions } = require('./config');

const mkdirp = promisify(mkdirpNode);

async function build () {
  await mkdirp(paths.dist);
  console.log(chalk.cyan('Generating main builds...'));

  let bundle = await rollup(configs.umdDev.input);
  let { code } = await bundle.generate(configs.umdDev.output);

  // generate main bundle.
  let outputPath = path.join(paths.dist, 'hello.js');
  fs.writeFileSync(outputPath, code);
  let stats = utils.stats({ code, path: outputPath });
  console.log(`${chalk.green('Output File:')} hello.js ${stats}`);

  // generate minified bundle.
  bundle = await rollup(configs.umdProd.input);
  code = (await bundle.generate(configs.umdProd.output)).code;

  outputPath = path.join(paths.dist, 'hello.min.js');
  fs.writeFileSync(outputPath, uglify.minify(code, uglifyOptions).code);
  stats = utils.stats({ code, path: outputPath });
  console.log(`${chalk.green('Output File:')} hello.min.js ${stats}`);


}

build();
